import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserInfo, login } from '@/api/user'

const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token// 存仓库
    setToken(token)// 持久化存本地
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  // 当token过期的时候清除token
  removeToken(state) {
    state.token = null
    // 删除token
    removeToken()
  },
  // 当token过期的时候清除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login({ commit }, obj) {
    // setTimeout(() => {
    //   commit('setToken', 'trrrfcdcv')
    // }, 3000)
    const res = await login(obj)
    // 拿到token存起来
    commit('setToken', res)
  },
  async getUserInfo({ commit }) {
    const res = await getUserInfo()
    commit('setUserInfo', res)
  },
  // 清除用户的token和数据,多个mutations的提交可以包在一个actions里面
  logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions

}
